package com.tencent.live.view.storage;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.object.PutObjectRequest;
import com.tencent.cos.xml.transfer.COSXMLDownloadTask;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.tencent.live.R;
import com.tencent.live.bean.upload.TokenBean;
import com.tencent.live.bean.upload.UploadResultBean;
import com.tencent.live.http.ContextHolder;
import com.tencent.live.http.HttpUtil;
import com.tencent.live.utils.FileUtil;
import com.tencent.live.utils.PicUtils;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class TenCentStorageActivity extends AppCompatActivity {

    private final int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 10001;
    private Bitmap mSelectedBitmap;
    private  int MAX_SIZE = 769;

    private CosXmlService cosXmlService;
    private TransferManager transferManager;

    private TokenBean.DataBean mDataBean;
    private ImageView mShowImg;

    private String mBucket;
    private String mRegion;
    private String mKey;
    private String mFileId;

    private String mPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tencent_storage);
        getSupportActionBar().hide();
        mShowImg = findViewById(R.id.img_show_edit);
        requestPermissions();
        fetchData();
        showLocalImg();
    }

    private void fetchData() {
        getUploadToken();
    }

    private void showLocalImg() {
        Uri uri = getIntent().getParcelableExtra("uri");
        mPhotoPath = FileUtil.getRealPathFromUri(this, uri);
        Log.i("yjj", "path >>>> " + mPhotoPath);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        try {

            InputStream inputStream = getContentResolver().openInputStream(uri);
            BitmapFactory.decodeStream(inputStream,null,options);
            inputStream.close();
            int height = options.outHeight;
            int width = options.outWidth;
            int sampleSize = 1;
            int max = Math.max(height,width);
            if (max > MAX_SIZE){
                int nw = width/2;
                int nh = height/2;
                while ((nw/sampleSize)> MAX_SIZE || (nh / sampleSize)>MAX_SIZE){
                    sampleSize *=2;
                }
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            mSelectedBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri),null,options);
            mShowImg.setVisibility(View.VISIBLE);
            mShowImg.setImageBitmap(mSelectedBitmap);

        } catch (IOException ioe) {
            Log.i("yjj", ioe.getMessage());
        }
    }



    public void onUploadClick(View view) {

        //String bucket = "vieewer-1301683607"; // 上传的 bucket 名称，region 为之前设置的 ap-guangzhou
        //String cosPath = "cosxml.jpg"; // 上传到 COS 的对象地址
        String cosPath = mKey;


        String localPath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera" + "/test.jpg";// 本地文件地址

        Log.i("yjj", "localPath~  = " + localPath);


        File file = new File(mPhotoPath);
        if(!file.exists()){
            Log.i("yjj","has not files" + mPhotoPath + ", key =" + mKey);
        } else {
            Log.i("yjj","has files" + mPhotoPath + ", key =" + mKey);
        }
        boolean b1 = file.exists();
        boolean b2 = file.isDirectory();
        boolean b3 = file.canRead();


        upload(mBucket, cosPath, mPhotoPath);
    }

    /**
     * 上传
     *
     * @params bucket  bucket 名称
     * @params cosPath 上传到 COS 的路径
     * @params localPath 本地文件路径
     */
    public void upload(String bucket, String cosPath, String localPath) {

        // 开始上传，并返回生成的 COSXMLUploadTask
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath,
                localPath, null);

        // 设置上传状态监听
        cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(final TransferState state) {
                // TODO: 2018/10/22
                Log.i("yjj","onStateChanged");
            }
        });

        // 设置上传进度监听
        cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(final long complete, final long target) {
                // TODO: 2018/10/22
                Log.i("yjj","onProgress" + complete);
            }
        });

        // 设置结果监听
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                // TODO: 文件上传到腾讯云存储桶完成后的回调
                Log.i("yjj","onSuccess");

                uploadFile();

            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                // TODO: 2018/10/22
                Log.i("yjj","onFail" + ">>> errorMessage = " + exception.errorMessage +
                        ", errorCode =" + exception.errorCode);
            }
        });
    }



    public void uploadSSECOS(String bucket, String cosPath, String localPath) {

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, localPath);
        putObjectRequest.setCOSServerSideEncryption();
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(putObjectRequest, null);
    }

    public void uploadSSEC(String bucket, String cosPath, String localPath, String customKey) {

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, localPath);
        try {
            putObjectRequest.setCOSServerSideEncryptionWithCustomerKey(customKey);
            COSXMLUploadTask cosxmlUploadTask = transferManager.upload(putObjectRequest, null);
        } catch (CosXmlClientException e) {
            e.printStackTrace();
        }

    }

    public void onDownloadClick(View view) {

        //String bucket = "vieewer-1301683607"; // 下载的 bucket 名称，region 为之前设置的 ap-guangzhou


   /*     String cosPath = "object.txt"; // 下载的 cos 上对象的路径
        String localDirPath = Environment.getExternalStorageDirectory().getAbsolutePath(); // 下载地址

        download(mBucket, mKey, localDirPath);*/
        downloadRequest();


    }

    public void download(String bucket, String cosPath, String localDirPath) {

        // 开始下载，并返回生成的 COSXMLDownloadTask
        COSXMLDownloadTask cosxmlDownloadTask = transferManager.download(this, bucket, cosPath,
                localDirPath);

        // 设置下载状态监听
        cosxmlDownloadTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(final TransferState state) {
                // TODO: 2018/10/22
                Log.i("yjj", "download onStateChanged");
            }
        });

        // 设置下载进度监听
        cosxmlDownloadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(final long complete, final long target) {
                // TODO: 2018/10/22
                Log.i("yjj", "download onProgress");
            }
        });

        // 设置下载结果监听
        cosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                // TODO: 2018/10/22
                Log.i("yjj", "download onSuccess");
            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                // TODO: 2018/10/22
                Log.i("yjj", "download onFail");
            }
        });
    }

    private void initCosService() {

        String region = "ap-shanghai"; // 设置 Bucket 的 region，后续上传下载的 bucket 的 region 都默认为 ap-shanghai
        if (mRegion != null && !"".equals(mRegion)) {
            region = mRegion;
        }
      /*  CosXmlServiceConfig cosXmlServiceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(region)
                .setDebuggable(true)
                .isHttps(true)
                .builder();

        *//**
         * 以下需要您自己搭建一个临时密钥服务来生成客户端所需的签名，搭建文档请参考：
         *
         * https://cloud.tencent.com/document/product/436/9068
         *//*
        QCloudCredentialProvider credentialProvider = null;
        try {
            credentialProvider = new SessionCredentialProvider(new HttpRequest.Builder<String>()
                    .url(new URL("your_auth_server_url")) // 您自己的签名服务器地址
                    .method("GET") // 注意这里的 HTTP method 为 GET，请根据您自己密钥服务的发布方式进行修改
                    .build());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }*/






        // 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(region)
                .isHttps(false) // 使用 HTTPS 请求, 默认为 HTTP 请求
                .builder();

        /**
         * 初始化 {@link QCloudCredentialProvider} 对象，来给 SDK 提供临时密钥
         */
        QCloudCredentialProvider credentialProvider = new MyCredentialProvider();

        if (mDataBean.getCredentials() != null) {
            ((MyCredentialProvider)credentialProvider).setTmpParams(mDataBean);
        }


        cosXmlService = new CosXmlService(this, serviceConfig, credentialProvider);




        //cosXmlService = new CosXmlService(this, cosXmlServiceConfig, credentialProvider);

        TransferConfig transferConfig = new TransferConfig.Builder().build();
        transferManager = new TransferManager(cosXmlService, transferConfig);
    }

    private void requestPermissions() {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        } else {
            Log.d("yjj", "requestMyPermissions: 有写SD权限");
        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        } else {
            Log.d("yjj", "requestMyPermissions: 有读SD权限");
        }

    }



    public void getUploadToken() {
        HttpUtil httpUtil = new HttpUtil(ContextHolder.getContext());
        String url = "https://api.vieewer.com/files/token/v1";
        httpUtil.setUrl(url);
        httpUtil.setListener(new HttpUtil.HttpUtilListener() {
            @Override
            public void onCancelled(Callback.CancelledException arg0) {

            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                String aa = arg0.toString();
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccess(String result) {
                try {

                    Gson gson = new GsonBuilder().create();
                    TokenBean ticketBean = gson.fromJson(result, TokenBean.class);
                    if ("200".equals(ticketBean.getCode())) {
                        mDataBean = ticketBean.getData();
                        mBucket = ticketBean.getData().getBucket();
                        mRegion = ticketBean.getData().getRegion();
                        mKey = ticketBean.getData().getKey();
                    }

                    initCosService();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).get();


    }



    private void uploadFile() {
        String localFileName = FileUtil.getFileNameWithSuffix(mPhotoPath);
        Log.i("yjj", "localFileName >>>" + localFileName);

        HttpUtil httpUtil = new HttpUtil(ContextHolder.getContext());
        JSONObject paramsObj = null;
        try {
            paramsObj = new JSONObject();
            paramsObj.put("name", localFileName);
            paramsObj.put("ossKey", mKey);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url = "https://api.vieewer.com/files/v1";
        httpUtil.setUrl(url);
        httpUtil.putjsonobject(paramsObj);


        httpUtil.setListener(new HttpUtil.HttpUtilListener() {
            @Override
            public void onCancelled(Callback.CancelledException arg0) {
                Log.i("yjj", "uploadFile onCancelled" + arg0.getMessage());

            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                Log.i("yjj", "uploadFile onError" + arg0.getMessage());

            }

            @Override
            public void onFinished() {
                Log.i("yjj", "uploadFile onFinished");
            }

            @Override
            public void onSuccess(String result) {
                Log.i("yjj", "uploadFile onSuccess" + result);
                Gson gson = new GsonBuilder().create();
                UploadResultBean uploadResultBean = gson.fromJson(result, UploadResultBean.class);
                if ("200".equals(uploadResultBean.getCode())) {
                    mFileId = uploadResultBean.getData().getId();
                }

                //todo 观众端上传完成后发送消息给主播端
                Intent data = new Intent();
                data.putExtra("fileId", mFileId);
                setResult(0, data);
                TenCentStorageActivity.this.finish();


            }
        }).post();

    }


    private void downloadRequest() {

        HttpUtil httpUtil = new HttpUtil(ContextHolder.getContext());

        String url = "https://api.vieewer.com/files/url/v1/" + mFileId ;
        httpUtil.setUrl(url);


        httpUtil.setListener(new HttpUtil.HttpUtilListener() {

            @Override
            public void onCancelled(Callback.CancelledException arg0) {
                Log.i("yjj", "downloadRequest onCancelled" + arg0.getMessage());

            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                Log.i("yjj", "downloadRequest onError" + arg0.getMessage());

            }

            @Override
            public void onFinished() {
                Log.i("yjj", "downloadRequest onFinished");
            }

            @Override
            public void onSuccess(String result) {
                Log.i("yjj", "downloadRequest onSuccess" + result);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    if ("200".equals(jsonObject.optString("code"))) {
                        String imgUrl = jsonObject.optString("data");
                        showImg(imgUrl);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

        }).get();


    }

    private void showImg(String imgUrl) {
        Log.i("yjj", "img url >>>>>>" + imgUrl);
        //PicUtils.savePic(TenCentStorageActivity.this, imgUrl);
        //PicUtils.load(TenCentStorageActivity.this, mDownloadImg, "http://www.jcodecraeer.com/uploads/20140731/67391406772378.png");

        RequestParams params = new RequestParams(imgUrl);

        // 默认缓存存活时间, 单位:毫秒（如果服务器没有返回有效的max-age或Expires则参考）
        params.setCacheMaxAge(1000 * 60);

        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                Log.i("yjj", "download onSuccess" + result.getPath());

                PicUtils.load(TenCentStorageActivity.this, mShowImg, result, true);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("yjj", "download onError");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.i("yjj", "download onCancelled");
            }

            @Override
            public void onFinished() {
                Log.i("yjj", "download onFinished");
            }


            @Override
            public void onWaiting() {
                Log.i("yjj", "download onWaiting");
            }

            @Override
            public void onStarted() {
                Log.i("yjj", "download onStarted 开始下载");
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                Log.i("yjj", "download onLoading");
            }

        });
    }





}
